//
//  Common.m
//  ON265
//
//  Created by Suto Dai on 12-4-12.
//  Copyright (c) 2012年 __MyCompanyName__. All rights reserved.
//

#import "Common.h"
//#import "SBJsonParser.h"
//#import "SBJsonWriter.h"
#import <CommonCrypto/CommonDigest.h>
#import <CommonCrypto/CommonCryptor.h>
#import <Foundation/Foundation.h>
#import <UIKit/UIKitDefines.h>

//#import "GTMBase64.h"
#import "BaseUrlConfig.h"

@implementation Common

#pragma mark - User
//是否登录
+(BOOL)isLogin
{
	NSString *userId = [[NSUserDefaults standardUserDefaults] valueForKey:Key_User_Id];
	if (userId == nil) {
		return NO;
	}
	return YES;
}

//得到用户登录ID
+(NSString *)getUserId
{
	return [[NSUserDefaults standardUserDefaults] valueForKey:@"id"];
}

//注销用户
+(void)logoutUser
{
    [[Common getUserDefaults] setValue:nil forKey:Key_User_Identity];
}

//得到用户上下文
+(NSUserDefaults *) getUserDefaults{
    NSUserDefaults *defaults = [NSUserDefaults standardUserDefaults];
    return defaults;
}

//设置用户上下文
+(void) setUserDefaults:(id) value key:(NSString *) key{
    NSUserDefaults *userDefaults = [Common getUserDefaults];
    [userDefaults setValue:value forKey:key];
}


#pragma mark - JSON
////JSON解析
//+(id)parserJsonString:(NSString *)jsonString
//{
//	SBJsonParser *parser = [[[SBJsonParser alloc] init] autorelease];
//	return [parser objectWithString:jsonString];
//}
//
////转化成JSON
//+(NSString *)jsonStringWithObject:(id)object
//{
//	SBJsonWriter *writer = [[[SBJsonWriter alloc] init] autorelease];
//	return [writer stringWithObject:object];
//}


#pragma mark - Encryption
//MD5 16位加密
+ (NSString *)md5_16:(NSString *)str
{
    const char *cStr = [str UTF8String];
    unsigned char result[16];
    CC_MD5( cStr, strlen(cStr), result );
    return [NSString stringWithFormat:
            @"%02X%02X%02X%02X%02X%02X%02X%02X%02X%02X%02X%02X%02X%02X%02X%02X",
            result[0], result[1], result[2], result[3], result[4], result[5], result[6], result[7],
            result[8], result[9], result[10], result[11], result[12], result[13], result[14], result[15]
            ];
}

//MD5 32位加密
+(NSString *)md5_32:(NSString *)str {
    const char *cStr = [str UTF8String];
    unsigned char result[32];
    CC_MD5( cStr, strlen(cStr), result );
    return [NSString stringWithFormat:
            @"%02X%02X%02X%02X%02X%02X%02X%02X%02X%02X%02X%02X%02X%02X%02X%02X",
            result[0], result[1], result[2], result[3],
            result[4], result[5], result[6], result[7],
            result[8], result[9], result[10], result[11],
            result[12], result[13], result[14], result[15]
            ];
}

//DES加密
+(NSString  *)DESPassword:(NSString *)pw WithKey:(NSString *)key_des{
    
    char buffer [1024] ;
    
    memset(buffer, 0, sizeof(buffer));
    
    size_t numBytesEncrypted ;
    
    unsigned int len_pw = [pw length];
    char plaintext[len_pw + 1];
    strcpy(plaintext, [pw UTF8String]); 
    
    unsigned int len_key = [key_des length];
    char key[len_key + 1];
    strcpy(key, [key_des UTF8String]);  
    CCCryptorStatus cryptStatus = CCCrypt(kCCEncrypt,  
                                          kCCAlgorithmDES,  
                                          kCCOptionPKCS7Padding | kCCOptionECBMode, 
                                          key,  
                                          kCCKeySizeDES, 
                                          NULL,  
                                          plaintext,  
                                          strlen(plaintext), 
                                          buffer,  
                                          1024, 
                                          &numBytesEncrypted);
    
    // 这里少了对返回值的判断：cryptStatus=kCCSuccess
    if (cryptStatus == kCCParamError) return @"PARAM ERROR";
    else if (cryptStatus == kCCBufferTooSmall) return @"BUFFER TOO SMALL";
    else if (cryptStatus == kCCMemoryFailure) return @"MEMORY FAILURE";
    else if (cryptStatus == kCCAlignmentError) return @"ALIGNMENT";
    else if (cryptStatus == kCCDecodeError) return @"DECODE ERROR";
    else if (cryptStatus == kCCUnimplemented) return @"UNIMPLEMENTED"; 
    
    NSData *data = [NSData dataWithBytes:buffer length:numBytesEncrypted];
    
    NSString *str1 = [data description];
    str1 = [str1 substringWithRange:NSMakeRange(1, [str1 length]-2)];
    
    str1=[[str1 stringByReplacingOccurrencesOfString:@" " withString:@""] uppercaseString]; 
    return    str1;
}


//#pragma mark - Coding
////Base64编码
//+ (NSString * )encodeBase64:(NSString * )input 
//{ 
//    NSData * data = [input dataUsingEncoding:NSUTF8StringEncoding allowLossyConversion:YES]; 
//    //转换到base64 
//    data = [GTMBase64 encodeData:data]; 
//    NSString * base64String = [[[NSString alloc] initWithData:data encoding:NSUTF8StringEncoding] autorelease]; 
//    return base64String; 
//}
//
////Base64解码
//+ (NSString *)decodeBase64:(NSString * )input 
//{ 
//    NSData * data = [input dataUsingEncoding:NSUTF8StringEncoding allowLossyConversion:YES]; 
//    //转换到base64 
//    data = [GTMBase64 decodeData:data]; 
//    NSString * base64String = [[[NSString alloc] initWithData:data encoding:NSUTF8StringEncoding] autorelease]; 
//    return base64String;
//}
//

#pragma mark - Else
/* China - CN
 * MCC    MNC    Brand    Operator                Status        Bands (MHz)                                    References and notes
 * 460    00            China Mobile            Operational    GSM 900/GSM 1800 UMTS (TD-SCDMA) 1880/2010
 * 460    01            China Unicom            Operational    GSM 900/GSM 1800/ UMTS 2100                    CDMA network sold to China Telecom, WCDMA commercial trial started in May 2009 and in full commercial operation as of October 2009.
 * 460    02            China Mobile            Operational    GSM 900/GSM 1800/ UMTS (TD-SCDMA) 1880/2010    
 * 460    03            China Telecom            Operational    CDMA 800/cdma evdo 2100    
 * 460    05            China Telecom            Operational        
 * 460    06            China Unicom            Operational    GSM 900/GSM 1800/UMTS 2100    
 * 460    07            China Mobile            Operational    GSM 900/GSM 1800/UMTS (TD-SCDMA) 1880/2010    
 * 460    20            China Tietong            Operational    GSM-R    
 * NA    NA            China Telecom&China Unicom    Operational        
 */
//得到运营商

//+ (NSString*)getCarrier
//{
//    UIDevice *myDevice = [UIDevice currentDevice];
//    NSString *imsi = [myDevice uniqueIdentifier];
//   // NSLog(@"imsi:%@", imsi);
//    if (imsi == nil || [imsi isEqualToString:@"SIM Not Inserted"] ) {
//        return @"0";
//    }
//    else {
//        if ([[imsi substringWithRange:NSMakeRange(0, 3)] isEqualToString:@"460"]) {
//            NSInteger MNC = [[imsi substringWithRange:NSMakeRange(3, 2)] intValue];
//            switch (MNC) {
//                case 00:
//                case 02:
//                case 07:
//                    return @"1"; //@"China Mobile" 移动
//                    break;
//                case 01:
//                case 06:    
//                    return @"2"; //@"China Unicom" 联通
//                    break;
//                case 03:
//                case 05:    
//                    return @"3"; //@"China Telecom" 电信
//                    break;
//                case 20:
//                    return @"4"; //@"China Tietong" 铁通
//                    break;
//                default:
//                    break;
//            }
//        }
//    }
//    return @"-1";
//}

////得到iOS版本
//+ (double) getSystemVersion{
//    double version = [[UIDevice currentDevice].systemVersion doubleValue];
//    return version;
//}
//
//得到文件路径
+ (NSString *) documentsFilePath:(NSString *) fileName {
	NSArray *paths = NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, YES);
	NSString *documentsDirectory = [paths objectAtIndex:0];
	return [documentsDirectory stringByAppendingPathComponent:fileName];
}

////给字符串间隔回车符
//+ (NSString *) stringWrap:(NSString *)Word
//{
//    NSMutableString *Temp = [[[NSMutableString alloc] init] autorelease];
//    int i = 0;
//    for (; i<[Word length]; i++) {
//        [Temp appendString:[Word substringWithRange:NSMakeRange(i, 1)]];
//        if ((i+1) % 4 == 0) {
//            [Temp appendFormat:@"\n"];
//        }
//    }
//    return Temp;
//}




@end
